/**<1>#############################################################################
 * fupload 插件
 * 说明：实现对Swfupload的封装。
 * 作者 张辉  
 * V1.0
 **#############################################################################*/
 var UPLOAD_BASE_PATH='/assets/plugins';//插件路径
 
(function($) {
    $.fn.fupload = function(options) {
        var defaults = {
            id: '',//页面元素ID
            session_id: '',//会话ID
            fupload_server: '',//上传服务器地址
            mfiles_server: '',//文件服务器地址
            params: {//上传参数
                'objectId': '',
                'groupCode': '',
				'thumb':'',//缩略图长*宽,auto自适应  "300*400,200*auto,auto*300"  默认 "auto*100,auto*300"
                'reset': false
            },
            but_name: '上传文件',//按钮名称
            fupload_url: '',//上传地址
            file_size: 1024 * 100,//文件大小
            types: "*",//文件类型
            pattern: "win", //上传模式 win 窗口模式 direct 页面直接上传模式;
            is_show_files: true,//是否展示文件列表
            limit: 10,//配置上传个数 默认10个
            upload_complete_fun: function() {}//回调函数 function(serverFileDataArray){}
        };
        //默认值 
        var opts = $.extend(defaults, options);
        return this.each(function() {
            var $this = $(this); //获取当前对象 
            var ids = {
				domId:opts.id,
                talbeId: "file_table_" + opts.id,
                toolbarId: "file_toolbar_" + opts.id,
                buttonCancelId: "file_cancel_" + opts.id,
                buttonHolderId: "file_holder_" + opts.id,
                uploadDlgId: "file_upload_dlg_" + opts.id,
                uploadProId: "file_upload_pro_" + opts.id,
                statusSpanId: "file_span_status_" + opts.id,
                swfu: "swfu_" + opts.id
            }

            if (opts.pattern == 'win') { //窗口上传
                initWinUploadHtml($this, opts, ids);
                initWinSwfUplod(opts, ids);
                $($this).bind("click",
                function() {
                    $("#" + ids.uploadProId + "").empty();
                    $("#" + ids.uploadDlgId + "").dialog('open');
                });
            }

            if (opts.pattern == 'direct') { //直接上传
                initDirectUploadHtml($this, opts, ids);
                initDirectSwfUplod(opts, ids);
            }
        });
    };

    //初始化直接上传HTML
    function initDirectUploadHtml($this, opts, ids) {
		//TO ADD
	};
    //--初始化直接上传HTML
    
	//初始化直接上传SWFUPLOAD
    function initDirectSwfUplod(opts, ids) {
        var settings = {
			dom_id:ids.domId,
			
            flash_url: STATIC_SERVER + UPLOAD_BASE_PATH+"/fupload/swfupload/js/swfupload.swf",
            upload_url: opts.fupload_url,
            post_params: opts.params,
            file_size_limit: opts.file_size,
            file_types: opts.types,
            file_types_description: "",
            file_upload_limit: opts.limit,
            file_queue_limit: 0,
            debug: false,
            button_image_url: STATIC_SERVER + UPLOAD_BASE_PATH +"/fupload/swfupload/images/upload_but_120_33.jpg",
            button_width: "120",
            button_height: "33",
            button_placeholder_id: "" + ids.buttonHolderId + "",
            button_text: '<span class="theFont">' + opts.but_name + '</span>',
            button_text_style: ".theFont { font-size:12px; color:#FFFFFF ; }",
            button_text_left_padding: 34,
            button_text_top_padding: 8,

            file_queued_handler: fileQueuedFull,
            file_queue_error_handler: fileQueueErrorFull,
            file_dialog_complete_handler: fileDialogCompleteFull,
            upload_start_handler: uploadStartFull,
            upload_progress_handler: uploadProgressFull,
            upload_error_handler: uploadErrorFull,
            upload_success_handler: uploadSuccessFull,
            upload_complete_handler: uploadCompleteFull,
            upload_complete_fun: opts.upload_complete_fun
        };
        settings.upload_url = settings.upload_url;
        ids.swfu = new SWFUpload(settings);

    };
    //--初始化直接上传SWFUPLOAD

    //初始化窗口上传所需HTML
    function initWinUploadHtml($this, opts, ids) {
        var txt = $($this).text();
        $($this).empty();
        var but_html = "<a href=\"javascript:void(0);\" class=\"btn btn-sky shiny\">" + "<i class=\"btn-label fa fa-upload\"></i>" + txt + "</a>";
        $($this).append(but_html);

        //创建表格
        if ($("#" + ids.talbeId + "").length == 0 && opts.is_show_files) {
            $($this).parent().append("<br/><div class='files-context' ><table class='files-table' style='width:800px'  id='" + ids.talbeId + "' ></table></div>");
            $("#" + ids.talbeId + "").datagrid({
                url: '',
                queryParams: opts.params,
                singleSelect: true,
                rownumbers: true,
                columns: [[{
                    field: 'fileUrl',
                    title: '预览',
                    width: 80,
                    formatter: function(value, rec) {
                        var view_html = "";
                        if (rec.fileType == '80A') {
                            view_html = "<img src='" + rec.fileUrl + "' height='60px;' />";
                        }
                        return view_html;
                    }
                },
                {
                    field: 'fileName',
                    title: '文件名称',
                    width: 400,
                    formatter: function(value, rec) {
                        return value + "." + rec.suffix;
                    }
                },
                {
                    field: 'fileSize',
                    title: '文件大小',
                    width: 80,
                    formatter: function(value, rec) {
                        return formatFileSize(value);
                    }
                },
                {
                    field: 'fileId',
                    title: '操作',
                    width: 180,
                    formatter: function(value, rec) {
                        var operate = "";
                        operate = operate + "<a href=\"javascript:removeFile('" +
						opts.fupload_server + "','" + ids.talbeId + "','" + value + "','" + 
						opts.params.objectId + "')\">删除</a>&nbsp;|&nbsp;";

                        if (rec.fileType == '80A') {
                            operate = operate + "<a href=\"javascript:showFiles('" + 
							opts.fupload_server + "','" + ids.uploadDlgId + "','" + value + "')\">查看</a>&nbsp;|&nbsp;";
                        }
                        operate = operate + "<a href=\"" + opts.fupload_server + '/uploadfile/download/' + value + "\">下载</a>";
                        return operate;
                    }
                }
                ]]
            });

            $.ajax({
                type: "post",
                url: opts.fupload_server + '/uploadfile/object-file-json',
                dataType: "jsonp",
                jsonp: "jsoncallback",
                data: opts.params,
                async: false,
                success: function(data) {
                    var jsonData = {
                        "total": 100,
                        "rows": data
                    };
                    $("#" + ids.talbeId + "").datagrid('loadData', jsonData);
                }
            });
        }
        //--创建表格

        //创建上传工具栏
        if ($("#" + ids.toolbarId + "").length == 0) {
            var toolBarHtml = "<div id='" + ids.toolbarId + "' style='padding:2px;'>" + "<span id='" + ids.buttonHolderId + "'></span>" + "<a style='display:none' id='" + ids.buttonCancelId + "' href='javascript:void(0)' onclick='" + ids.swfu + ".cancelQueue()' >取消所有上传</a>" + "<span id=\"" + ids.statusSpanId + "\" class='uploadMsg'>0 个文件已上传</span> " + "<div class='clr'></div>" + "</div>";

            $("body").append(toolBarHtml);
        }
        //--创建上传工具栏
        //创建进度列表
        if ($("#" + ids.uploadDlgId + "").length == 0) {
            var dlgHtml = "<div class='progress-dlg' id='" + ids.uploadDlgId + "' >" + "<div class=\"progress-content\">" + "<div class=\"progress-head\">" + "<div class=\"uploadFileName\">文件名</div>" + "<div class=\"uploadFileSize\">文件大小</div>" + "<div class=\"uploadProgress\">进度</div>" + "<div class=\"uploadStatus\">状态</div>" + "<div class=\"uploadOperate\" >操作</div>" + "<div style=\"clear:both;\"></div>" + "</div>" + "<div id=\"" + ids.uploadProId + "\" class=\"progress-body\"></div>" + "</div>" + "</div>";
            $("body").append(dlgHtml);

            $("#" + ids.uploadDlgId + "").dialog({
                iconCls: 'icon-upload',
                closed: true,
                modal: true,
                title: "上传附件",
                toolbar: '#' + ids.toolbarId + '',
                onClose: function() { //关闭上传窗口
                    var jsonData = {};
                    //跨域请求
                    $.ajax({
                        type: "post",
                        url: opts.fupload_server + '/uploadfile/object-file-json',
                        dataType: "jsonp",
                        jsonp: "jsoncallback",
                        data: opts.params,
                        async: false,
                        success: function(data) {
                            jsonData = {
                                "total": 100,
                                "rows": data
                            };
                        }
                    });
                    if (opts.is_show_files) {
                        var params = opts.params;
                        var queryParams = $('#' + ids.talbeId + '').datagrid('options').queryParams;
                        queryParams.objectId = params.objectId;
                        //$("#"+ids.talbeId+"").datagrid('reload'); 
                        $("#" + ids.talbeId + "").datagrid('loadData', jsonData);

                    }
                    opts.upload_complete_fun(jsonData.rows);

                }
            });
        }
        //--创建进度列表
    };
    //--初始化窗口上传所需HTML

    //初始化窗口上传swfupload
    function initWinSwfUplod(opts, ids) {
        var settings = {
			dom_id:ids.domId,
			
            flash_url: STATIC_SERVER +UPLOAD_BASE_PATH+ "/fupload/swfupload/js/swfupload.swf",
            upload_url: opts.fupload_url,
            post_params: opts.params,
            file_size_limit: opts.file_size,
            file_types: opts.types,
            file_types_description: "",
            file_upload_limit: opts.limit,
            //配置上传个数
            file_queue_limit: 0,
            custom_settings: {
                progressTarget: ids.uploadProId,
                cancelButtonId: ids.buttonCancelId,
                statusTarget: ids.statusSpanId
            },
            debug: false,
            // Button settings
            button_image_url: STATIC_SERVER +UPLOAD_BASE_PATH+ "/fupload/swfupload/images/upload_but_120_33.jpg",
            button_width: "120",
            button_height: "33",
            button_placeholder_id: "" + ids.buttonHolderId + "",
            button_text: '<span class="theFont">' + opts.but_name + '</span>',
            button_text_style: ".theFont { font-size:12px;color:#FFFFFF; }",
            button_text_left_padding: 34,
            button_text_top_padding: 8,

            file_queued_handler: fileQueued,
            file_queue_error_handler: fileQueueError,
            file_dialog_complete_handler: fileDialogComplete,
            upload_start_handler: uploadStart,
            upload_progress_handler: uploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: uploadSuccess,
            upload_complete_handler: uploadComplete,
            queue_complete_handler: queueComplete
        };
        ids.swfu = new SWFUpload(settings);
    };
    //--初始化窗口上传swfupload
})(jQuery);

function formatFileSize(size) {
    var unit = "B";
    if (size > (1024 * 1024 * 1024)) {
        unit = "GB";
        size /= (1024 * 1024 * 1024);
    } else if (size > (1024 * 1021)) {
        unit = "MB";
        size /= (1024 * 1024);
    } else if (size > 1024) {
        unit = "KB";
        size /= 1024;
    }
    var fsize = size.toFixed(2) + " " + unit;
    return fsize;
}
//删除文件
function removeFile(fupload_server, tableId, fileId, objectId) {
    var url = fupload_server + '/uploadfile/' + fileId + "/deleteAll";
    $.ajax({
        type: "post",
        url: url,
        dataType: "jsonp",
        jsonp: "jsoncallback",
        async: false,
        success: function(data) {
            if (data.success == 'unexists') {
                alert("文件不存在");
            }
            var queryParams = $('#' + tableId + '').datagrid('options').queryParams;
            queryParams.objectId = objectId;
            //跨域请求
            $.ajax({
                type: "post",
                url: fupload_server + '/uploadfile/object-file-json',
                dataType: "jsonp",
                jsonp: "jsoncallback",
                data: queryParams,
                async: false,
                success: function(dta) {
                    var jsonData = {
                        "total": 100,
                        "rows": dta
                    };
                    $("#" + tableId + "").datagrid('loadData', jsonData);
                }
            });
        }
    });
}
function showFiles(fupload_server, uploadDlgId, fileId) {
    var url = fupload_server + '/uploadfile/' + fileId + "/url";
    var imgurl = "";
    $.ajax({
        type: "post",
        url: url,
        dataType: "jsonp",
        jsonp: "jsoncallback",
        async: false,
        success: function(data) {
            imgurl = data.fileUrl;
            var img_html = "<div style='text-align:center' ><img src='" + imgurl + "' height='340'  /></div>";
            var imageshow_id = "imageshow_" + uploadDlgId;
            if ($("#" + imageshow_id).length <= 0) {
                var imageshow_html = "<div id='" + imageshow_id + "' class='easyui-window'  >" + img_html + "</div>";
                $("body").append(imageshow_html);

                $('#' + imageshow_id).window({
                    //$("#"+imageshow_id).windbow({
                    iconCls: 'icon-image',
                    modal: true,
                    closed: false,
                    width: 700,
                    height: 400,
                    title: '图片预览',
                    resizable: true
                });
            } else {
                $("#" + imageshow_id).empty();
                $("#" + imageshow_id).append(img_html);
            }
            $("#" + imageshow_id + "").dialog('open');
        }
    });
}

//HELPER
var FilesHelper = {
    getFilesIdArray: function(objectId, groupCode, fun) {
        var url = UPLOAD_SERVER + '/uploadfile/' + objectId + "/file-json";
        $.ajax({
            type: "post",
            url: url,
            dataType: "jsonp",
            jsonp: "jsoncallback",
            data: {
                'groupCode': groupCode
            },
            async: false,
            success: function(data) {
                var filesIdArray = new Array();
                for (var i = 0; i < data.length; i++) {
                    filesIdArray[i] = data[i].filesId;
                }
                fun(filesIdArray);
            }
        });
    },
    getFileUrlArray: function(objectId, groupCode, fun) {
        var url = UPLOAD_SERVER + '/uploadfile/' + objectId + "/file-json";
        $.ajax({
            type: "post",
            url: url,
            dataType: "jsonp",
            jsonp: "jsoncallback",
            data: {
                'groupCode': groupCode
            },
            async: false,
            success: function(data) {
                var fileUrlArray = new Array();
                for (var i = 0; i < data.length; i++) {
                    fileUrlArray[i] = data.url;
                }
                fun(fileUrlArray);
            }
        });
    },

    getIndexFileUrl: function(objectId, groupCode, fun) {

        var url = UPLOAD_SERVER + '/uploadfile/' + objectId + "/file-json";
        $.ajax({
            type: "post",
            url: url,
            dataType: "jsonp",
            jsonp: "jsoncallback",
            data: {
                'groupCode': groupCode
            },
            async: false,
            success: function(data) {
                var fileUrl = "";
                if (data.length > 0) {
                    fileUrl = data[0].url;
                }
                fun(fileUrl);
            }
        });
    },

    getFileUrl: function(fileId, fun) {
        var url = UPLOAD_SERVER + '/uploadfile/' + fileId + "/url";
        $.ajax({
            type: "post",
            url: url,
            dataType: "jsonp",
            jsonp: "jsoncallback",
            async: false,
            success: function(data) {
                var imgurl = data.fileUrl;
                fun(imgurl);
            }
        });
    }
}

//util
var PathUtil = {
    toWebPath: function(path) {
        var regex = new RegExp("/{1,}|\\\\{1,}", "g");
        var separator = "/";
        var replacement = "/";
        path = path.replace(regex, replacement);
        if (path.indexOf(separator) == 0) {
            path = path.substring(1, path.length());
        }
        path = path.replace("http:/", "http://");
        return path;
    },
    joinWebPath: function(pathArray) {
        var newPath = "";
        for (var i = 0; i < pathArray.length; i++) {
            var path = pathArray[i];
            path = PathUtil.toWebPath(path);
            if ((path.lastIndexOf("/") + 1) != path.length && i != (pathArray.length - 1)) {
                path = path + "/";
            }
            newPath = newPath + path;
        }
        return newPath;
    }
}






/**<2>#############################################################################
 * swfupload plug 
 * by 张辉 2015-10-29 
 **#############################################################################*/


var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.queue = {};
	
	SWFUpload.prototype.initSettings = (function (oldInitSettings) {
		return function () {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}
			
			this.customSettings.queue_cancelled_flag = false;
			this.customSettings.queue_upload_count = 0;
			
			this.settings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			
			this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function (fileID) {
		this.customSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", false, [fileID]);
	};

	SWFUpload.prototype.cancelQueue = function () {
		
		this.customSettings.queue_cancelled_flag = true;
		this.stopUpload();
		
		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};
	
	SWFUpload.queue.uploadCompleteHandler = function (file) {
		var user_upload_complete_handler = this.settings.user_upload_complete_handler;
		var continueUpload;

		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.customSettings.queue_upload_count++;
		}

		if (typeof(user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
		} else {
			continueUpload = true;
		}
		
		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0 && this.customSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.customSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler", [this.customSettings.queue_upload_count]);
				this.customSettings.queue_upload_count = 0;
			} else {
				this.customSettings.queue_cancelled_flag = false;
				this.customSettings.queue_upload_count = 0;
			}
		}
	};
}




/**
 *  	清空上传数插件
 *      var swf = new SWFUpload(settings);
 *      swf.subUploadedCount(1); // 递减 一个已经上传成功的数量;
 *      swf.plusUploadedCount(1); // 加 一个已经上传成功的数量;
 *      swf.resetUploadedCount(); // 重置 已经上传成功的数量,即为0;
 */
if (typeof(SWFUpload) === "function") {

    //     减 上传成功的文件总数
    //    @param optCount 要移除的数量
    //    @auhtor WUYF
    SWFUpload.prototype.subUploadedCount = function(optCount){
          var stats = this.getStats();
          stats.successful_uploads = stats.successful_uploads - optCount;
          if(stats.successful_uploads < 0){
              stats.successful_uploads = 0;
          }
          this.setStats(stats);
    };
    
    //     加 上传成功的文件总数
    //    @param optCount 要添加的数量
    //    @auhtor WUYF
    SWFUpload.prototype.plusUploadedCount = function(optCount){
          var stats = this.getStats();
          stats.successful_uploads = stats.successful_uploads + optCount;
          this.setStats(stats);
    };
    
    //     重置 上传成功的文件总数
    //    @auhtor WUYF
    SWFUpload.prototype.resetUploadedCount = function(){
          var stats = this.getStats();
          stats.successful_uploads = 0;
          this.setStats(stats);
    };
}






/**<3>#############################################################################
 * swfupload 进度条插件
 * by zhanghui 2015-10-29
 **#############################################################################*/
function fileQueued(file) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("等待上传...");
        progress.toggleCancel(true, this);

    } catch(ex) {
        this.debug(ex);
    }
}

function fileQueueError(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            alert("您正在上传的文件队列过多.\n" + (message === 0 ? "您已达到上传限制": "您最多能选择 " + (message > 1 ? "上传 " + message + " 文件.": "一个文件.")));
            return;
        }

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            progress.setStatus("文件尺寸过大.");
            this.debug("错误代码: 文件尺寸过大, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            progress.setStatus("无法上传零字节文件.");
            this.debug("错误代码: 零字节文件, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            progress.setStatus("不支持的文件类型.");
            this.debug("错误代码: 不支持的文件类型, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        default:
            if (file !== null) {
                progress.setStatus("未处理的错误");
            }
            this.debug("错误代码: " + errorCode + ", 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        }
    } catch(ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        if (numFilesSelected > 0) {
            document.getElementById(this.customSettings.cancelButtonId).disabled = false;
        }
        /* I want auto start the upload and I can do that here */
        this.startUpload();

    } catch(ex) {
        this.debug(ex);
    }
}

function uploadStart(file) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("开始上传...");
        progress.toggleCancel(true, this);
    } catch(ex) {}

    return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

    try {
        var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setProgress(percent);
        progress.setStatus("正在上传...");
    } catch(ex) {
        this.debug(ex);
    }
}

function uploadSuccess(file, serverData) {

    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("上传成功");
        progress.toggleCancel(false);

    } catch(ex) {
        this.debug(ex);
    }
	this.resetUploadedCount();
}

function uploadError(file, errorCode, message) {

    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
            progress.setStatus("上传错误: " + message);
            this.debug("错误代码: HTTP错误, 文件名: " + file.name + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
            progress.setStatus("上传失败");
            this.debug("错误代码: 上传失败, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
            progress.setStatus("服务器 (IO) 错误");
            this.debug("错误代码: IO 错误, 文件名: " + file.name + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
            progress.setStatus("安全错误");
            this.debug("错误代码: 安全错误, 文件名: " + file.name + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            progress.setStatus("超出上传限制.");
            this.debug("错误代码: 超出上传限制, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
            progress.setStatus("无法验证.  跳过上传.");
            this.debug("错误代码: 文件验证失败, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            // If there aren't any files left (they were all cancelled) disable the cancel button
            if (this.getStats().files_queued === 0) {
                document.getElementById(this.customSettings.cancelButtonId).disabled = true;
            }
            progress.setStatus("取消");
            progress.setCancelled();
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
            progress.setStatus("停止");
            break;
        default:
            progress.setStatus("未处理的错误: " + errorCode);
            this.debug("错误代码: " + errorCode + ", 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 信息: " + message);
            break;
        }
    } catch(ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {

    if (this.getStats().files_queued === 0) {
        document.getElementById(this.customSettings.cancelButtonId).disabled = true;
    }
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {

    var statusId = this.customSettings.statusTarget;
    var status = document.getElementById(statusId);
    status.innerHTML = numFilesUploaded + " 个文件" + (numFilesUploaded === 1 ? "": " ") + "已上传";
}




/**
* 独立页面上传方法
**/
//当一个文件被添加到上传队列时会触发此事件，提供的唯一参数为包含该文件信息的file object对象
function fileQueuedFull(file) {
	
}
//当文件添加到上传队列失败时触发此事件，失败的原因可能是文件大小超过了你允许的数值、文件是空的或者文件队列已经满员了等。
//该事件提供了三个参数。第一个参数是当前出现问题的文件对象，第二个参数是具体的错误代码，可以参照SWFUpload.QUEUE_ERROR中定义的常量
function fileQueueErrorFull(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            alert("您正在上传的文件队列过多.\n" + (message === 0 ? "您已达到上传限制": "您最多能选择 " + (message > 1 ? "上传 " + message + " 文件.": "一个文件.")));
            return;
        }
    } catch(ex) {
        this.debug(ex);
    }
}
/**
当文件选取完毕且选取的文件经过处理后（指添加到上传队列），会立即触发该事件。可以在该事件中调用this.startUpload()方法来实现文件的自动上传
参数number of files selected指本次在文件选取框里选取的文件数量
参数number of files queued指本次被添加到上传队列的文件数量
参数total number of files in the queued指当前上传队列里共有多少个文件（包括了本次添加进去的文件）
**/
function fileDialogCompleteFull(numFilesSelected, numFilesQueued) {
    try {
        /* I want auto start the upload and I can do that here */
        this.startUpload();

    } catch(ex) {
        this.debug(ex);
    }
}
/**
当文件即将上传时会触发该事件,该事件给了你在文件上传前的最后一次机会来验证文件信息、增加要随之上传的附加信息或做其他工作。可以通过返回false来取消本次文件的上传
参数file object为当前要上传的文件的信息对象
**/
function uploadStartFull(file) {
	
    try {
        $("#" + this.settings.dom_id).find(".upmsg").addClass("loading");
    } catch(ex) {}
    return true;
}
/**
该事件会在文件的上传过程中反复触发，可以利用该事件来实现上传进度条
参数file object为文件信息对象
参数bytes complete为当前已上传的字节数
参数total bytes为文件总的字节数
**/
function uploadProgressFull(file, bytesLoaded, bytesTotal) {
    try {

	} catch(ex) {
        this.debug(ex);
    }
}
/**
当一个文件上传成功后会触发该事件
参数file object为文件信息对象
参数server data为服务器端输出的数据
**/
function uploadSuccessFull(file, serverData) {
	//console.log(this);
	this.resetUploadedCount();
}
/**
文件上传被中断或是文件没有成功上传时会触发该事件。停止、取消文件上传或是在uploadStart事件中返回false都会引发这个事件，但是如果某个文件被取消了但仍然还在队列中则不会触发该事件
参数file object为文件信息对象
参数error code为错误代码，具体的可参照SWFUpload.UPLOAD_ERROR中定义的常量
**/
function uploadErrorFull(file, errorCode, message) {
    try {

} catch(ex) {
        this.debug(ex);
    }
}
/**
当一次文件上传的流程完成时（不管是成功的还是不成功的）会触发该事件，该事件表明本次上传已经完成，上传队列里的下一个文件可以开始上传了。该事件发生后队列中下一个文件的上传将会开始
**/
function uploadCompleteFull(file) {
    var bthis = this;
    $("#" + this.settings.dom_id).find(".upmsg").removeClass("loading");
    //$("#uploadProId").html("上传成功...");
    //onUploadComplete(this.settings.post_params);
    //跨域请求
    $.ajax({
        type: "post",
        url: UPLOAD_SERVER + '/uploadfile/object-file-json',
        dataType: "jsonp",
        jsonp: "jsoncallback",
        data: bthis.settings.post_params,
        async: false,
        success: function(data) {
            bthis.settings.upload_complete_fun(data);
        }
    });
}


function queueCompleteFull(numFilesUploaded) {

}







/**<4>#############################################################################
 * swfupload 进度条
 * by zhanghui 
 **#############################################################################*/

function FileProgress(file, targetID) {
	this.fileProgressID = file.id;

	this.opacity = 100;
	this.height = 0;
	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progress-tr";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";


		var uploadFileName = document.createElement("div");
		uploadFileName.className = "uploadFileName";
		uploadFileName.appendChild(document.createTextNode(file.name));
		
		var uploadFileSize = document.createElement("div");
		uploadFileSize.className = "uploadFileSize";
		var size = file.size; 
		var unit = "B";
		if(size>(1024*1024*1024)){
			unit="GB";
			size /=(1024*1024*1024);
		}else if(size>(1024*1021)){
			unit="MB";
			size /=(1024*1024);
		}else if(size>1024){
			unit="KB";
			size /=1024;
		}
		var fsize=size.toFixed(2)+" "+unit;
		uploadFileSize.appendChild(document.createTextNode(fsize));

		

		var uploadProgress = document.createElement("div");
		uploadProgress.className = "uploadProgress";
		var progressContainer=document.createElement("div");
		progressContainer.className = "progressContainerInProgress";
		var progressPercent=document.createElement("div");
		progressPercent.className = "progressBarInProgress";
		progressContainer.appendChild(progressPercent);
		uploadProgress.appendChild(progressContainer);

		var uploadStatus = document.createElement("div");
		uploadStatus.className = "uploadStatus";
		uploadStatus.innerHTML = "&nbsp;";
		
		var uploadOperate = document.createElement("div");
		uploadOperate.className = "uploadOperate";
		var cancelButton = document.createElement("a");
		cancelButton.className = "progressCancel";
		cancelButton.href = "#";
		cancelButton.style.visibility = "hidden";
		cancelButton.appendChild(document.createTextNode(" "));
		uploadOperate.appendChild(cancelButton);
		
		this.fileProgressElement.appendChild(uploadFileName);
		this.fileProgressElement.appendChild(uploadFileSize);
		this.fileProgressElement.appendChild(uploadProgress);
		this.fileProgressElement.appendChild(uploadStatus);
		this.fileProgressElement.appendChild(uploadOperate);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer bggreen";
	this.fileProgressElement.childNodes[2].childNodes[0].className = "progressContainerInProgress";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].style.width = percentage + "%";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].innerHTML=percentage + "%";
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer bgblue";
	this.fileProgressElement.childNodes[2].childNodes[0].className = "progressContainerComplete";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].className = "progressBarComplete";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].style.width = "100%";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].innerHTML= "100%";
	/**
	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 10000);
	**/
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer bgred";
	this.fileProgressElement.childNodes[2].childNodes[0].className = "progressContainerError";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].className = "progressBarError";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].style.width = "";
	//this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].innerHTML= "0%";
	/**
	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 5000);
	**/
};
FileProgress.prototype.setCancelled = function () {
	
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[2].childNodes[0].className = "progressContainerError";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].className = "progressBarError";
	this.fileProgressElement.childNodes[2].childNodes[0].childNodes[0].style.width = "";
	
	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 2000);
	
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[3].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[4].childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[4].childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		setTimeout(function () {
			oSelf.disappear();
		}, rate);
	} else {
		this.fileProgressWrapper.style.display = "none";
	}
};